#include "parafluidmesh.h"
#include "parafluidvector.h"

#include <QBuffer>
#include <QByteArray>
#include <QFile>
#include <QIODevice>
#include <QList>

using namespace ParaFluid;

Mesh::~Mesh()
{
	/* does nothing */
}

Mesh::Mesh()
	: triangles()
{
	/* does nothing */
}

Mesh::Mesh(const QString & objFile)
	: triangles()
{
	loadFile(objFile);
}

Mesh::Mesh(const Mesh & other)
	: triangles(other.triangles)
{
	/* does nothing */
}

Mesh & Mesh::operator= (const Mesh & rhs)
{
	if(&rhs != this)
	{
		triangles = rhs.triangles;
	}
	return *this;
}

void Mesh::loadFile(const QString & objFile)
{
	QFile file(objFile);
	
	if(file.exists())
	{
		if(file.open(QIODevice::ReadOnly | QIODevice::Text))
		{
			QList<Vector> vertices;
			
			while(!file.atEnd())
			{
				QByteArray line = file.readLine();
				
				QList<QByteArray> words = line.split(' ');
				
				if(words.size() >= 4)
				{
					words[0].replace(10, "");
					words[0].replace(13, "");
					
					if(words.at(0).at(0) == 'v')
					{
						words[3].replace(10, "");
						words[3].replace(13, "");
						
						bool ok = true;
						float x = words.at(1).toFloat(&ok);
						float y = words.at(2).toFloat(&ok);
						float z = words.at(3).toFloat(&ok);
						if(ok)
						{
							vertices.append(Vector(x, y, z));
						}
					}
					else if(words.at(0).at(0) == 'f')
					{
						words[3].replace(10, "");
						words[3].replace(13, "");
						
						bool ok = true;
						int face1 = words.at(1).toInt(&ok);
						int face2 = words.at(2).toInt(&ok);
						int face3 = words.at(3).toInt(&ok);
						if(ok)
						{
							triangles.append(Triangle(vertices.at(face1 - 1), vertices.at(face2 - 1), vertices.at(face3 - 1)));
						}
					}
				}
			}
		}
	}
}
